package net.contrend.system.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import net.contrend.system.dao.UserDao;
import net.contrend.system.form.UserForm;
import net.contrend.util.BaseAction;

public class UserAction extends BaseAction {
    
    private UserDao userDao;
    
    private void initDao() {
        if (null == this.userDao) {
            this.userDao = (UserDao) this.getBean("userDao");
        }
    }
    
    public ActionForward insert(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        this.initDao();
        
        DynaActionForm df = (DynaActionForm) form;
        UserForm user = (UserForm) df.get(this.ACTION_FORM_NAME);
        int i = this.userDao.insert(user);
        request.setAttribute("ACTION_RESULT", i);
        
        return mapping.findForward(this.ACTION_PAGE_EDIT);
    }
    
    public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        this.initDao();
        
        DynaActionForm df = (DynaActionForm) form;
        UserForm user = (UserForm) df.get(this.ACTION_FORM_NAME);
        int i = this.userDao.update(user);
        request.setAttribute("ACTION_RESULT", i);
        
        return mapping.findForward(this.ACTION_PAGE_EDIT);
    }
    
    public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        this.initDao();
        
        String userId = request.getParameter("userId");
        int i = this.userDao.delete(userId);
        response.getWriter().write(String.valueOf(i));
        
        return null;
    }
    
    public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        this.initDao();
        
        String userId = request.getParameter("userId");
        DynaActionForm df = (DynaActionForm) form;
        df.set(this.ACTION_FORM_NAME, this.userDao.query(userId));
        
        return mapping.findForward(this.ACTION_PAGE_EDIT);
    }
    
}
